// index.js
// 获取应用实例
const { HTTP } = require('../../utils/http');
const app = getApp()
const { api } = require('../../utils/api');
const { fromNowFormat } = require('../../utils/filter');
const { request } = new HTTP();

Page({
  data: {
    indicatorDots: true,
    vertical: false,
    autoplay: false,
    interval: 2000,
    duration: 500,

    vipIcon: '../../images/crownProfile.png',
    noMessage: '../../images/',
    active: 0,
    // type: recommend-推荐，new-最新，anonymity-匿名
    tabs: [
      {type: 'recommend', name: '推荐', page: -1},
      {type: 'new', name: '最新', page: -1},
      {type: 'anonymity', name: '匿名', page: -1},
    ],
    isLoad: true,
    userInfo: {},
    isLogin: false,

    focus: false,
    
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  toDetail(event){
    wx.navigateTo({
      url: "../squareDetail/index?id=" + event.currentTarget.dataset.id
    })
  },
  onShow(){
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1    // 根据tab的索引值设置
      }) 
    }
    console.log('---onShow---')
    // tabs: [
    //   {type: 'recommend', name: '推荐', page: -1},
    //   {type: 'new', name: '最新', page: -1},
    //   {type: 'anonymity', name: '匿名', page: -1},
    // ],
    this.initPageData()
    this._getThems()

  },

  // 重置数据
  initPageData(){
    this.setData({
      tabs: [
        {type: 'recommend', name: '推荐', page: -1},
        {type: 'new', name: '最新', page: -1},
        {type: 'anonymity', name: '匿名', page: -1},
      ]
    })
  },
  /*
  onLoad() {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  */
 /*
 getUserInfo(e) {
   console.log(e)
   app.globalData.userInfo = e.detail.userInfo
   this.setData({
     userInfo: e.detail.userInfo,
     hasUserInfo: true
   })
 },
 */
 onLoad() {
   console.log('---isLogin')
   console.log(app.globalData.isLogin)
  //  this._queryUserPublish();
   this._getThems()
  },

  // 发布按钮
  publish() {
    console.log('--publish--')
    wx.navigateTo({url: '../publishNews/index'});
  },
  // 获取用户已发布的话题分类
  async _queryUserPublish() {
    let {returnCode = '', beans = []} = await request({
      url: api.queryUserPublish,
      method: 'get',
      data: {}
    });
    if (returnCode === '0000') {
      beans = beans.map(item => {
        item.themes = [];
        item.page = -1;
        return item;
      })
      console.log('---beans--')
      console.log(beans)
      this.setData({
        tabs: beans
      });
      if (beans[0].totals > 0) {
        this._getThems();
      }
    }
  },
   // 查询详情
   async _showDetail(id, index) {
    let {returnCode = '', bean = {}} = await request({
      url: `/api/theme/${id}`,
      method: 'get',
      data: {}
    });
    console.log('--bean--')
    console.log(bean)
    console.log(this.data.tabs[this.data.active].themes)
    let listObj = this.data.tabs
    let list = this.data.tabs[this.data.active].themes
    list[index].isLike = bean.isLike
    list[index].likeCount = bean.likeCount
    // list.splice(index, 1, bean)
    listObj[this.data.active].themes = list
    this.setData({tabs: listObj})
    // list.splice(index,1, bean)
    // this.data.tabs[this.data.active].themes.splice(index,1,bean)
    
  },
  // 获取分类接口
  async _getThems() {
    if (!this.data.isLoad) return;
    console.log('---active--')
    console.log(this.data.active, )
    const pageKey = `tabs[${this.data.active}].page`;
    const currentPage = this.data.tabs[this.data.active].page + 1;
    this.setData({[pageKey]: currentPage});

    // 参数
    const type = this.data.tabs[this.data.active].type;
    // console
    // let typeObj = {
    //   1
    // }
    const params = {
      page: currentPage,
      count: 4,
      sex: 0,
      type: type + ''
    };
    if (!params.category_id) delete params.category_id;

    wx.showNavigationBarLoading();
    wx.setNavigationBarTitle({title: '加载中...'});
    let {returnCode = '', beans = []} = await request({
      url: api.themeSquare,
      method: 'get',
      data: params
    });
    wx.hideNavigationBarLoading();
    wx.setNavigationBarTitle({title: '他说'});
    if (returnCode === '0000') {
      if (beans.item.length === 0) {
        this.setData({isLoad: false});
        return;
      }
      beans.item.map(item => {
        item.fromNowFormatTime = fromNowFormat(item.create_time);
        return item;
      });
      const key = `tabs[${this.data.active}].themes`;
      const haveValues = this.data.tabs[this.data.active].themes;
      this.setData({
        [key]: Object.prototype.toString.call(haveValues) == "[object Array]" ? [...haveValues, ...beans.item] : beans.item
      });
    }
  },
   // 话题喜欢信息
   async _themetlike(id, isLike, index) {
    let {returnCode = '', beans = {}} = await request({
      url: `/api/like/theme/${id}`,
      method: 'get',
      data: {}
    });


    if(returnCode == '0000'){
      if(isLike) {
        wx.showToast({
          title: '取消点赞',
          icon: 'none',
          duration: 2000
        })
      }else{
        wx.showToast({
          title: '点赞成功',
          icon: 'success',
          duration: 2000
        })
      }
      console.log('---this.data.tabs[this.data.active]-')
      console.log(index)
      // this.data.tabs[this.data.active]

      // this.data.tabs[this.data.active].themes && this.data.tabs[this.data.active].themes.forEach((item, idx) => {
      //   if(item.id  === id) {
      //     let act = this.data.active
      //     this.setData({
      //       [`tabs[act].themes[idx].isLike`]: !isLike
      //     })
      //   }
      // })

      // this.initPageData()
      // this._getThems();
     let detail =  this._showDetail(id,index)
     console.log('---detail--')
     console.log(detail)

    }


  },
  // 详情点赞
  clickLike(otps) {
    console.log(otps)
    // this._themeDislike()
    this._themetlike(otps.target.dataset.id, otps.target.dataset.islike, otps.target.dataset.index )
  },
  onChange(event) {
    const { detail: {index} } = event;
    this.setData({active: index, isLoad: true});
    this.initPageData()
    this._getThems();
  },

  // 触底加载
  onReachBottom() {
    this._getThems();
  },
  shareClick() {
    console.log('---shareClick')
    // wx.showShareMenu({
    //   withShareTicket: true,
    //   menus: ['shareAppMessage', 'shareTimeline']
    // })
    
  },


  clickFocus() {
    console.log('--clickFocus')
    this.setData({
      focus: true
    })
  },
  onShareAppMessage: function (res) {
    console.log('---res---')
    console.log(res)
    return {
      title: "快来看，好家伙！",
      path: "pages/squareDetail/index?id=" + res.target.dataset.id + '&isShare=1'
    }
  }
  
})
